
#Hospital Management System REST API


from flask import Flask, request, jsonify
from flask_cors import CORS
import sys
import os

current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(os.path.dirname(current_dir))
sys.path.insert(0, project_root)

from src.database.connection import HospitalDatabase

app = Flask(__name__)
CORS(app)

db = HospitalDatabase()
if not db.connect():
    print("Failed to connect to database")
    exit(1)

def success_response(data, message="Success", status_code=200):
    return jsonify({"success": True, "message": message, "data": data}), status_code

def error_response(message, status_code=400):
    return jsonify({"success": False, "error": message}), status_code

# ✓ PATIENT CRUD ENDPOINTS | 患者增删改查接口

@app.route('/api/patients', methods=['GET'])
def get_all_patients():
    try:
        page = request.args.get('page', 1, type=int)
        limit = request.args.get('limit', 10, type=int)
        search = request.args.get('search', '', type=str)
        
        patients = db.search_patients(search) if search else db.get_all_patients()
        
        patient_list = []
        for patient in patients:
            patient_list.append({
                'patient_id': patient[0],
                'first_name': patient[1],
                'last_name': patient[2],
                'date_of_birth': str(patient[3]) if patient[3] else None,
                'gender': patient[4],
                'blood_group': patient[5],
                'address': patient[6],
                'email': patient[7],
                'phone': patient[8],
                'emergency_contact': patient[9],
                'emergency_phone': patient[10],
                'medical_history': patient[11],
                'registration_date': str(patient[12]) if patient[12] else None,
                'status': patient[13]
            })
        
        start, end = (page - 1) * limit, page * limit
        paginated_patients = patient_list[start:end]
        
        return success_response({
            'patients': paginated_patients,
            'total': len(patient_list),
            'page': page,
            'limit': limit
        })
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/patients/<int:patient_id>', methods=['GET'])
def get_patient(patient_id):
    try:
        patient = db.get_patient(patient_id)
        
        if not patient:
            return error_response("Patient not found", 404)
        
        patient_data = {
            'patient_id': patient[0],
            'first_name': patient[1],
            'last_name': patient[2],
            'date_of_birth': str(patient[3]) if patient[3] else None,
            'gender': patient[4],
            'blood_group': patient[5],
            'address': patient[6],
            'email': patient[7],
            'phone': patient[8],
            'emergency_contact': patient[9],
            'emergency_phone': patient[10],
            'medical_history': patient[11],
            'registration_date': str(patient[12]) if patient[12] else None,
            'status': patient[13]
        }
        
        return success_response(patient_data)
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/patients', methods=['POST'])
def create_patient():
    try:
        data = request.get_json()
        
        required = ['first_name', 'last_name', 'date_of_birth', 'gender', 'address', 'phone']
        for field in required:
            if field not in data:
                return error_response(f"Missing field: {field}", 400)
        
        patient_id = db.add_patient(
            first_name=data['first_name'],
            last_name=data['last_name'],
            date_of_birth=data['date_of_birth'],
            gender=data['gender'],
            blood_group=data.get('blood_group'),
            address=data['address'],
            email=data.get('email'),
            phone=data['phone'],
            emergency_contact=data.get('emergency_contact'),
            emergency_phone=data.get('emergency_phone'),
            medical_history=data.get('medical_history')
        )
        
        if patient_id:
            return success_response({'patient_id': patient_id}, "Patient created successfully", 201)
        else:
            return error_response("Failed to create patient", 500)
    except Exception as e:
        return error_response(str(e), 400)

@app.route('/api/patients/<int:patient_id>', methods=['PUT'])
def update_patient(patient_id):
    try:
        data = request.get_json()
        if not db.get_patient(patient_id):
            return error_response("Patient not found", 404)
        
        if db.update_patient(patient_id, **data):
            return success_response({'patient_id': patient_id}, "Patient updated successfully")
        else:
            return error_response("Failed to update patient", 500)
    except Exception as e:
        return error_response(str(e), 400)

@app.route('/api/patients/<int:patient_id>', methods=['DELETE'])
def delete_patient(patient_id):
    try:
        if not db.get_patient(patient_id):
            return error_response("Patient not found", 404)
        
        if db.delete_patient(patient_id):
            return success_response(None, "Patient deleted successfully")
        else:
            return error_response("Failed to delete patient", 500)
    except Exception as e:
        return error_response(str(e), 500)

# ✓ STAFF CRUD ENDPOINTS | 员工增删改查接口

@app.route('/api/staff', methods=['GET'])
def get_all_staff():
    try:
        search = request.args.get('search', '', type=str)
        staff_list = db.search_medical_staff(search) if search else db.get_all_medical_staff()
        
        staff_data = []
        for staff in staff_list:
            staff_data.append({
                'staff_id': staff[0],
                'first_name': staff[1],
                'last_name': staff[2],
                'email': staff[3],
                'phone': staff[4],
                'specialization': staff[5],
                'dept_id': staff[6],
                'hire_date': str(staff[7]) if staff[7] else None,
                'salary': float(staff[8]) if staff[8] else None,
                'status': staff[9],
                'license_number': staff[10]
            })
        
        return success_response({'staff': staff_data, 'total': len(staff_data)})
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/staff/<string:staff_id>', methods=['GET'])
def get_staff_member(staff_id):
    try:
        staff = db.get_medical_staff(staff_id)
        
        if not staff:
            return error_response("Staff member not found", 404)
        
        staff_data = {
            'staff_id': staff[0],
            'first_name': staff[1],
            'last_name': staff[2],
            'email': staff[3],
            'phone': staff[4],
            'specialization': staff[5],
            'dept_id': staff[6],
            'hire_date': str(staff[7]) if staff[7] else None,
            'salary': float(staff[8]) if staff[8] else None,
            'status': staff[9],
            'license_number': staff[10]
        }
        
        return success_response(staff_data)
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/staff', methods=['POST'])
def create_staff():
    try:
        data = request.get_json()
        
        required = ['staff_id', 'first_name', 'last_name', 'email', 'phone', 'specialization', 'dept_id', 'salary']
        for field in required:
            if field not in data:
                return error_response(f"Missing required field: {field}", 400)
        
        if db.add_medical_staff(
            staff_id=data['staff_id'],
            first_name=data['first_name'],
            last_name=data['last_name'],
            email=data['email'],
            phone=data['phone'],
            specialization=data['specialization'],
            dept_id=data['dept_id'],
            salary=data['salary'],
            license_number=data.get('license_number')
        ):
            return success_response({'staff_id': data['staff_id']}, "Staff member created successfully", 201)
        else:
            return error_response("Failed to create staff member", 500)
    except Exception as e:
        return error_response(str(e), 400)

# ✓ APPOINTMENT CRUD ENDPOINTS | 预约增删改查接口

@app.route('/api/appointments', methods=['GET'])
def get_all_appointments():
    try:
        date = request.args.get('date', '', type=str)
        appointments = db.get_appointments_by_date(date) if date else db.get_all_appointments()
        
        appointment_list = []
        for appt in appointments:
            appointment_list.append({
                'appointment_id': appt[0],
                'patient_id': appt[1],
                'staff_id': appt[2],
                'appointment_date': str(appt[3]) if appt[3] else None,
                'appointment_time': str(appt[4]) if appt[4] else None,
                'duration_minutes': appt[5],
                'status': appt[6],
                'notes': appt[7]
            })
        
        return success_response({'appointments': appointment_list, 'total': len(appointment_list)})
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/appointments/<int:appointment_id>', methods=['GET'])
def get_appointment(appointment_id):
    try:
        db.cursor.execute("""
            SELECT a.*, p.first_name, p.last_name, ms.first_name, ms.last_name
            FROM appointments a
            JOIN patients p ON a.patient_id = p.patient_id
            JOIN medical_staff ms ON a.staff_id = ms.staff_id
            WHERE a.appointment_id = %s
        """, (appointment_id,))
        
        appt = db.cursor.fetchone()
        
        if not appt:
            return error_response("Appointment not found", 404)
        
        appointment_data = {
            'appointment_id': appt[0],
            'patient_id': appt[1],
            'staff_id': appt[2],
            'appointment_date': str(appt[3]) if appt[3] else None,
            'appointment_time': str(appt[4]) if appt[4] else None,
            'duration_minutes': appt[5],
            'status': appt[6],
            'notes': appt[7],
            'patient_name': f"{appt[9]} {appt[10]}",
            'staff_name': f"{appt[11]} {appt[12]}"
        }
        
        return success_response(appointment_data)
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/appointments', methods=['POST'])
def create_appointment():
    try:
        data = request.get_json()
        
        required = ['patient_id', 'staff_id', 'appointment_date', 'appointment_time']
        for field in required:
            if field not in data:
                return error_response(f"Missing required field: {field}", 400)
        
        appointment_id = db.add_appointment(
            patient_id=data['patient_id'],
            staff_id=data['staff_id'],
            appointment_date=data['appointment_date'],
            appointment_time=data['appointment_time'],
            duration_minutes=data.get('duration_minutes', 30),
            notes=data.get('notes')
        )
        
        if appointment_id:
            return success_response({'appointment_id': appointment_id}, "Appointment created successfully", 201)
        else:
            return error_response("Failed to create appointment", 500)
    except Exception as e:
        return error_response(str(e), 400)

@app.route('/api/appointments/<int:appointment_id>', methods=['PUT'])
def update_appointment(appointment_id):
    try:
        data = request.get_json()
        set_clauses, values = [], []
        for key, value in data.items():
            if value is not None and key != 'appointment_id':
                set_clauses.append(f"{key} = %s")
                values.append(value)
        
        if not set_clauses:
            return error_response("No fields to update", 400)
        
        values.append(appointment_id)
        query = f"UPDATE appointments SET {', '.join(set_clauses)} WHERE appointment_id = %s"
        
        db.cursor.execute(query, values)
        db.conn.commit()
        
        return success_response({'appointment_id': appointment_id}, "Appointment updated successfully")
    except Exception as e:
        db.conn.rollback()
        return error_response(str(e), 500)

@app.route('/api/appointments/<int:appointment_id>', methods=['DELETE'])
def delete_appointment(appointment_id):
    try:
        db.cursor.execute("DELETE FROM appointments WHERE appointment_id = %s", (appointment_id,))
        db.conn.commit()
        
        if db.cursor.rowcount == 0:
            return error_response("Appointment not found", 404)
        
        return success_response(None, "Appointment deleted successfully")
    except Exception as e:
        db.conn.rollback()
        return error_response(str(e), 500)

# ✓ ROOM CRUD ENDPOINTS | 房间增删改查接口

@app.route('/api/rooms', methods=['GET'])
def get_all_rooms():
    try:
        available = request.args.get('available', '', type=str)
        room_type = request.args.get('room_type', '', type=str)
        
        rooms = db.get_available_rooms() if available == 'true' else db.get_all_rooms()
        
        room_list = []
        for room in rooms:
            room_list.append({
                'room_id': room[0],
                'room_number': room[1],
                'room_type': room[2],
                'capacity': room[3],
                'rate_per_day': float(room[4]) if room[4] else None,
                'floor_number': room[5],
                'is_available': room[6],
                'dept_id': room[7]
            })
        
        if room_type:
            room_list = [r for r in room_list if r['room_type'] == room_type]
        
        return success_response({'rooms': room_list, 'total': len(room_list)})
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/rooms/<int:room_id>', methods=['GET'])
def get_room(room_id):
    try:
        db.cursor.execute("SELECT * FROM rooms WHERE room_id = %s", (room_id,))
        room = db.cursor.fetchone()
        
        if not room:
            return error_response("Room not found", 404)
        
        room_data = {
            'room_id': room[0],
            'room_number': room[1],
            'room_type': room[2],
            'capacity': room[3],
            'rate_per_day': float(room[4]) if room[4] else None,
            'floor_number': room[5],
            'is_available': room[6],
            'dept_id': room[7]
        }
        
        return success_response(room_data)
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/rooms', methods=['POST'])
def create_room():
    try:
        data = request.get_json()
        
        required = ['room_number', 'room_type', 'capacity', 'rate_per_day']
        for field in required:
            if field not in data:
                return error_response(f"Missing required field: {field}", 400)
        
        if db.add_room(
            room_number=data['room_number'],
            room_type=data['room_type'],
            capacity=data['capacity'],
            rate_per_day=data['rate_per_day'],
            floor_number=data.get('floor_number'),
            dept_id=data.get('dept_id')
        ):
            return success_response({'room_number': data['room_number']}, "Room created successfully", 201)
        else:
            return error_response("Failed to create room", 500)
    except Exception as e:
        return error_response(str(e), 400)

# ✓ INVOICE CRUD ENDPOINTS | 账单增删改查接口

@app.route('/api/invoices', methods=['GET'])
def get_all_invoices():
    try:
        status = request.args.get('status', '', type=str)
        patient_id = request.args.get('patient_id', '', type=int)
        
        if patient_id:
            db.cursor.execute("""
                SELECT * FROM invoices WHERE patient_id = %s ORDER BY invoice_date DESC
            """, (patient_id,))
        else:
            invoices = db.get_all_invoices()
        
        if patient_id:
            invoices = db.cursor.fetchall()
        
        invoice_list = []
        for inv in invoices:
            invoice_list.append({
                'invoice_id': inv[0],
                'patient_id': inv[1],
                'appointment_id': inv[2],
                'invoice_date': str(inv[3]) if inv[3] else None,
                'due_date': str(inv[4]) if inv[4] else None,
                'subtotal': float(inv[5]) if inv[5] else None,
                'tax_amount': float(inv[6]) if inv[6] else None,
                'total_amount': float(inv[7]) if inv[7] else None,
                'status': inv[8],
                'payment_date': str(inv[9]) if inv[9] else None,
                'payment_method': inv[10]
            })
        
        if status:
            invoice_list = [i for i in invoice_list if i['status'] == status]
        
        return success_response({'invoices': invoice_list, 'total': len(invoice_list)})
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/invoices/<int:invoice_id>', methods=['GET'])
def get_invoice(invoice_id):
    try:
        db.cursor.execute("""
            SELECT i.*, p.first_name, p.last_name
            FROM invoices i
            JOIN patients p ON i.patient_id = p.patient_id
            WHERE i.invoice_id = %s
        """, (invoice_id,))
        
        inv = db.cursor.fetchone()
        
        if not inv:
            return error_response("Invoice not found", 404)
        
        invoice_data = {
            'invoice_id': inv[0],
            'patient_id': inv[1],
            'appointment_id': inv[2],
            'invoice_date': str(inv[3]) if inv[3] else None,
            'due_date': str(inv[4]) if inv[4] else None,
            'subtotal': float(inv[5]) if inv[5] else None,
            'tax_amount': float(inv[6]) if inv[6] else None,
            'total_amount': float(inv[7]) if inv[7] else None,
            'status': inv[8],
            'payment_date': str(inv[9]) if inv[9] else None,
            'payment_method': inv[10],
            'patient_name': f"{inv[12]} {inv[13]}"
        }
        
        return success_response(invoice_data)
    except Exception as e:
        return error_response(str(e), 500)

# ✓ COMPLEX QUERY ENDPOINTS | 复杂查询接口
# ✓ Complex Queries (5%): JOINs, GROUP BY, aggregates, CTEs | 复杂查询 (5%): 连接、分组、聚合、公共表表达式

@app.route('/api/reports/revenue-by-department', methods=['GET'])
def revenue_by_department():
    try:
        db.cursor.execute("""
            SELECT 
                d.dept_name,
                d.dept_id,
                COUNT(DISTINCT a.appointment_id) as total_appointments,
                COALESCE(SUM(i.total_amount), 0) as total_revenue,
                COALESCE(AVG(i.total_amount), 0) as avg_revenue_per_appointment
            FROM departments d
            LEFT JOIN medical_staff ms ON d.dept_id = ms.dept_id
            LEFT JOIN appointments a ON ms.staff_id = a.staff_id
            LEFT JOIN invoices i ON a.appointment_id = i.appointment_id
            WHERE i.status = 'paid' OR i.status IS NULL
            GROUP BY d.dept_id, d.dept_name
            HAVING COUNT(DISTINCT a.appointment_id) >= 0
            ORDER BY total_revenue DESC
        """)
        
        results = db.cursor.fetchall()
        
        report_data = []
        for row in results:
            report_data.append({
                'department_name': row[0],
                'department_id': row[1],
                'total_appointments': row[2],
                'total_revenue': float(row[3]) if row[3] else 0,
                'avg_revenue_per_appointment': float(row[4]) if row[4] else 0
            })
        
        return success_response({
            'report': report_data,
            'total_departments': len(report_data)
        })
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/reports/doctor-workload', methods=['GET'])
def doctor_workload():
    try:
        start_date = request.args.get('start_date', '2025-01-01', type=str)
        end_date = request.args.get('end_date', '2025-12-31', type=str)
        min_appointments = request.args.get('min_appointments', 0, type=int)
        
        db.cursor.execute("""
            SELECT 
                ms.staff_id,
                ms.first_name || ' ' || ms.last_name as doctor_name,
                ms.specialization,
                d.dept_name,
                COUNT(DISTINCT a.appointment_id) as total_appointments,
                COUNT(DISTINCT a.patient_id) as unique_patients,
                COUNT(CASE WHEN a.status = 'completed' THEN 1 END) as completed_appointments,
                COUNT(CASE WHEN a.status = 'cancelled' THEN 1 END) as cancelled_appointments
            FROM medical_staff ms
            LEFT JOIN departments d ON ms.dept_id = d.dept_id
            LEFT JOIN appointments a ON ms.staff_id = a.staff_id 
                AND a.appointment_date BETWEEN %s AND %s
            WHERE ms.specialization LIKE '%%Doctor%%' OR ms.specialization LIKE '%%Physician%%' 
                OR ms.specialization LIKE '%%Surgeon%%' OR ms.specialization LIKE '%%ologist'
            GROUP BY ms.staff_id, ms.first_name, ms.last_name, ms.specialization, d.dept_name
            HAVING COUNT(DISTINCT a.appointment_id) >= %s
            ORDER BY total_appointments DESC
        """, (start_date, end_date, min_appointments))
        
        results = db.cursor.fetchall()
        
        workload_data = []
        for row in results:
            workload_data.append({
                'staff_id': row[0],
                'doctor_name': row[1],
                'specialization': row[2],
                'department': row[3],
                'total_appointments': row[4],
                'unique_patients': row[5],
                'completed_appointments': row[6],
                'cancelled_appointments': row[7]
            })
        
        return success_response({
            'workload_report': workload_data,
            'period': {'start_date': start_date, 'end_date': end_date},
            'total_doctors': len(workload_data)
        })
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/reports/outstanding-invoices', methods=['GET'])
def outstanding_invoices():
    try:
        db.cursor.execute("""
            WITH patient_balances AS (
                SELECT 
                    p.patient_id,
                    p.first_name || ' ' || p.last_name as patient_name,
                    p.phone,
                    p.email,
                    COUNT(i.invoice_id) as total_invoices,
                    SUM(i.total_amount) as total_owed,
                    MIN(i.due_date) as earliest_due_date,
                    MAX(i.due_date) as latest_due_date
                FROM patients p
                INNER JOIN invoices i ON p.patient_id = i.patient_id
                WHERE i.status IN ('pending', 'overdue')
                GROUP BY p.patient_id, p.first_name, p.last_name, p.phone, p.email
            )
            SELECT * FROM patient_balances
            WHERE total_owed > 0
            ORDER BY total_owed DESC
        """)
        
        results = db.cursor.fetchall()
        
        outstanding_data = []
        total_outstanding = 0
        for row in results:
            amount = float(row[5]) if row[5] else 0
            total_outstanding += amount
            outstanding_data.append({
                'patient_id': row[0],
                'patient_name': row[1],
                'phone': row[2],
                'email': row[3],
                'total_invoices': row[4],
                'total_owed': amount,
                'earliest_due_date': str(row[6]) if row[6] else None,
                'latest_due_date': str(row[7]) if row[7] else None
            })
        
        return success_response({
            'outstanding_invoices': outstanding_data,
            'total_patients': len(outstanding_data),
            'total_outstanding_amount': total_outstanding
        })
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/reports/medication-stock', methods=['GET'])
def medication_stock_report():
    try:
        low_stock_only = request.args.get('low_stock', 'false', type=str)
        
        query = """
            SELECT 
                medication_id,
                medication_name,
                generic_name,
                dosage_form,
                strength,
                stock_quantity,
                min_stock_level,
                unit_price,
                (stock_quantity * unit_price) as inventory_value,
                expiry_date,
                CASE 
                    WHEN stock_quantity = 0 THEN 'OUT_OF_STOCK'
                    WHEN stock_quantity <= min_stock_level THEN 'LOW_STOCK'
                    WHEN stock_quantity <= min_stock_level * 2 THEN 'MODERATE'
                    ELSE 'SUFFICIENT'
                END as stock_status
            FROM medications
        """
        
        if low_stock_only == 'true':
            query += " WHERE stock_quantity <= min_stock_level"
        
        query += " ORDER BY stock_quantity ASC, expiry_date ASC"
        
        db.cursor.execute(query)
        results = db.cursor.fetchall()
        
        medications = []
        for row in results:
            medications.append({
                'medication_id': row[0],
                'medication_name': row[1],
                'generic_name': row[2],
                'dosage_form': row[3],
                'strength': row[4],
                'stock_quantity': row[5],
                'min_stock_level': row[6],
                'unit_price': float(row[7]) if row[7] else 0,
                'inventory_value': float(row[8]) if row[8] else 0,
                'expiry_date': str(row[9]) if row[9] else None,
                'stock_status': row[10]
            })
        
        return success_response({
            'medications': medications,
            'total_items': len(medications)
        })
    except Exception as e:
        return error_response(str(e), 500)

# ✓ SEARCH ENDPOINTS | 搜索接口

@app.route('/api/patients/search', methods=['GET'])
def search_patients():
    try:
        name = request.args.get('name', '', type=str)
        blood_group = request.args.get('blood_group', '', type=str)
        
        query = "SELECT * FROM patients WHERE 1=1"
        params = []
        
        if name:
            query += " AND (first_name ILIKE %s OR last_name ILIKE %s)"
            params.extend([f'%{name}%', f'%{name}%'])
        
        if blood_group:
            query += " AND blood_group = %s"
            params.append(blood_group)
        
        query += " ORDER BY first_name, last_name"
        
        db.cursor.execute(query, params)
        patients = db.cursor.fetchall()
        
        patient_list = []
        for patient in patients:
            patient_list.append({
                'patient_id': patient[0],
                'first_name': patient[1],
                'last_name': patient[2],
                'date_of_birth': str(patient[3]) if patient[3] else None,
                'gender': patient[4],
                'blood_group': patient[5],
                'phone': patient[8]
            })
        
        return success_response({'patients': patient_list, 'total': len(patient_list)})
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/appointments/available', methods=['GET'])
def available_appointments():
    try:
        date = request.args.get('date', '', type=str)
        staff_id = request.args.get('staff_id', '', type=str)
        
        if not date or not staff_id:
            return error_response("date and staff_id required", 400)
        
        db.cursor.execute("""
            SELECT appointment_time, duration_minutes
            FROM appointments
            WHERE staff_id = %s AND appointment_date = %s AND status != 'cancelled'
            ORDER BY appointment_time
        """, (staff_id, date))
        
        booked_slots = db.cursor.fetchall()
        
        all_slots = [f"{h:02d}:{m:02d}:00" for h in range(9, 17) for m in [0, 30]]
        booked_times = [str(slot[0]) for slot in booked_slots]
        available_slots = [s for s in all_slots if s not in booked_times]
        
        return success_response({
            'date': date,
            'staff_id': staff_id,
            'available_slots': available_slots,
            'booked_slots': booked_times
        })
    except Exception as e:
        return error_response(str(e), 500)

@app.route('/api/health', methods=['GET'])
def health_check():
    try:
        db.cursor.execute("SELECT 1")
        db_status = "connected"
    except:
        db_status = "disconnected"
    
    return success_response({
        'status': 'running',
        'database': db_status,
        'version': '1.0.0'
    })

@app.route('/', methods=['GET'])
def index():
    return success_response({
        'message': 'Hospital Management System REST API',
        'version': '1.0.0',
        'endpoints': {
            'patients': '/api/patients',
            'staff': '/api/staff',
            'appointments': '/api/appointments',
            'rooms': '/api/rooms',
            'invoices': '/api/invoices',
            'reports': '/api/reports/*',
            'health': '/api/health'
        },
        'documentation': '/api/documentation'
    })

@app.errorhandler(404)
def not_found(error):
    return error_response("Endpoint not found", 404)

@app.errorhandler(500)
def internal_error(error):
    return error_response("Internal server error", 500)

if __name__ == '__main__':
    print("=" * 60)
    print("Hospital Management System REST API")
    print("Server: http://localhost:5000")
    print("=" * 60)
    app.run(host='0.0.0.0', port=5000, debug=True)

